from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from pprint import pprint

from common.database import get_db
from core.response import resp_200, resp_400
from core.logger import logger

from app.celery_task.handlers.celery_task_handler import CeleryTaskHandler
from core.security import permission_checker

from app.celery_task.schemas import *


router = APIRouter()



#### celery异步任务操作 ####
@router.get('/task/', summary="获取celery异步任务信息, 根据表字段-模糊匹配", description="异步任务")
async def get_celery_task_search(field: str = Query("all", description="查询的字段名称"), value: str = Query("", description="字段值"),
                              page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
                              db: Session = Depends(get_db), user=Depends(permission_checker)):
    celery_task_handler = CeleryTaskHandler()
    result = celery_task_handler.get_celery_task_search(db, page, per_page, field, value)
    if not result:
        message = "get celery task search failed"
        logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
        return resp_400(message)
    return resp_200(result)


@router.get('/task/match/', summary="获取celery异步任务信息, 根据表字段-完全匹配", description="异步任务")
async def get_celery_task_match(field: str = Query("all", description="查询的字段名称"), value: str = Query("", description="字段值"),
                              page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
                              db: Session = Depends(get_db), user=Depends(permission_checker)):
    celery_task_handler = CeleryTaskHandler()
    result = celery_task_handler.get_celery_task_match(db, page, per_page, field, value)
    if not result:
        message = "get celery task search failed"
        logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
        return resp_400(message)
    return resp_200(result)


@router.delete('/task/', summary="删除异步任务", description="异步任务")
async def delete_celery_task(data: DelBaseModel, db: Session = Depends(get_db), user=Depends(permission_checker)):
    celery_task_handler = CeleryTaskHandler()
    result = celery_task_handler.delete_celery_task(db, data.dict())
    if not result:
        message = "delete celery task failed"
        logger.error(f"{message} => data:{data}")
        return resp_400(message)
    return resp_200()


